<template>
  <div class="has-foot-pb">
    <div class="user-info">
      <div class="left">
        <!-- {{ detail.customerName }} -->
        <span>{{ filterPhone(detail.customerPhone) }}</span>
      </div>
      <div class="right" @click.stop="onCallPhone(detail.customerPhone)">
        <img class="icon" src="@/assets/images/phone.png" />
      </div>
    </div>

    <div class="header"><span class="border"></span>客户基本信息</div>
    <div>
      <Cell
        title="客户名称"
        v-model="formData.customerName"
        divider
        :required="isHandover"
        :right="false"
        :isInput="true"
        :maxlength="20"
        input-align="right"
        placeholder="输入客户名称"
      />
      <Cell
        title="身份证号"
        v-model="formData.customerIdcard"
        divider
        :required="isHandover"
        :right="false"
        :isInput="true"
        :maxlength="18"
        input-align="right"
        placeholder="输入身份证号"
      />
      <FieldSelect
        v-model="formData.customerSex"
        :required="isHandover"
        title="性别"
        label-name="label"
        value-name="value"
        :optionData="[
          { label: '男', value: 1 },
          { label: '女', value: 0 }
        ]"
        clear
      />
      <Cell
        title="年龄"
        :required="isHandover"
        v-model="formData.customerAge"
        divider
        :right="false"
        :isInput="true"
        input-align="right"
        placeholder="输入年龄"
      />
      <Cell title="是否有店面" :custom="true" :right="false">
        <qmp-switch v-model="formData.isHaveShop" :active-value="1" :inactive-value="0">
          <template #background>
            <span class="qmp-switch__background"> {{ formData.isHaveShop === 1 ? '是' : '否' }}</span>
          </template>
        </qmp-switch>
      </Cell>
      <Cell
        title="店面总面积"
        v-model="formData.shopArea"
        divider
        :right="false"
        :isInput="true"
        input-align="right"
        placeholder="输入店面总面积"
        :maxlength="10"
      />
      <FieldSelect
        v-model="formData.followUpType"
        title="跟进方式"
        :url="`/data-dict/app/v2/dictionary/CTM_FOLLOW_UP_TYPE`"
        label-name="dictName"
        value-name="dictCode"
        method="get"
        :params="dictParams"
        clear
      />
      <Cell title="招商经理" :modelValue="detail.managerName" readonly />

      <Cell :modelValue="detail.allotTime" title="意向客户分配时间" placeholder="选择意向客户分配时间" readonly />

      <FieldSelect
        v-model="formData.intendedLevel"
        title="意向等级"
        class="other-cell"
        subTitle="A类：确定与全友合作意向，有合作实力，有合适口岸，可快速签约；
B类：明确与全友合作意向，但可能资金不足或口岸不达标；
C类：有明确投资意向，对全友或其他竞品品牌；"
        :url="`/data-dict/app/v2/dictionary/CTM_INTENTION_LEVEL`"
        label-name="dictName"
        value-name="dictCode"
        method="get"
        :params="dictParams"
        clear
      />
      <FieldSelect
        :required="isHandover"
        v-model="formData.intendedBusiness"
        title="意向经营业务类型"
        :url="`/app/v1/mdmService/custDocDef/page`"
        label-name="name"
        value-name="code"
        method="post"
        :params="{ query: { custDocCode: 'QY037' }, type: 0 }"
        :multiple="true"
        clear
      />
      <Cell
        title="意向加盟城市"
        v-model="formData.intendedCity"
        divider
        :right="false"
        :isInput="true"
        input-align="right"
        placeholder="输入意向加盟城市"
        :maxlength="50"
      />
      <FieldSelect
        v-model="formData.agencyCode"
        v-model:label="formData.agencyName"
        title="所属办事处"
        :required="isHandover"
        :url="`/app/v1/user/organization/agencies`"
        label-name="name"
        value-name="code"
        method="get"
        clear
      />
      <Cell title="特别备注" is-column custom divider :right="false">
        <qmp-field v-model="formData.specialRemarks" type="textarea" placeholder="输入内容" class="ctm-text-area" />
      </Cell>
      <FieldSelect
        v-model="formData.customerSource"
        title="客户来源"
        :url="`/data-dict/app/v2/dictionary/CTM_TOBE_CUSTOMER_DATA_FROM`"
        label-name="dictName"
        value-name="dictCode"
        method="get"
        :params="dictParams"
        clear
      />
      <Cell title="现经营品牌/行业资历" is-column custom divider :right="false">
        <qmp-field
          v-model="formData.industryQualification"
          type="textarea"
          placeholder="输入内容"
          class="ctm-text-area"
          :maxlength="200"
        />
      </Cell>
      <Cell
        title="意向开店面积"
        v-model="formData.intendedShopArea"
        divider
        :required="isHandover"
        :right="false"
        :isInput="true"
        input-align="right"
        placeholder="输入面积"
        :maxlength="10"
      />
      <Cell title="跟进说明" is-column custom divider :right="false">
        <qmp-field
          v-model="formData.description"
          type="textarea"
          placeholder="输入内容"
          class="ctm-text-area"
          :maxlength="200"
        />
      </Cell>

      <Cell title="意向商家情况描述" is-column custom divider :right="false">
        <qmp-field
          v-model="formData.intendedMerchantDescription"
          type="textarea"
          :required="isHandover"
          placeholder="输入内容"
          class="ctm-text-area"
          :maxlength="200"
        />
      </Cell>
    </div>
    <div class="header"><span class="border"></span>特许经营市场信息</div>
    <Cell
      title="特许经营市场"
      :modelValue="formData.marketName"
      divider
      :right="true"
      :required="isHandover"
      :isInput="false"
      input-align="right"
      placeholder="请选择"
      @right="onClickToChoice"
    />

    <Cell title="城市级别" :modelValue="detail.cityLevel" dictTypeCode="CITY_LEVEL" readonly />
    <Cell title="市场属性" :modelValue="detail.marketNatrue" dictTypeCode="MARKET_NATURE" readonly />

    <Cell title="是否有场地" :custom="true" :right="false" :required="isHandover">
      <qmp-switch v-model="formData.isSite" :active-value="1" :inactive-value="0">
        <template #background>
          <span class="qmp-switch__background"> {{ formData.isSite === 1 ? '是' : '否' }}</span>
        </template>
      </qmp-switch>
    </Cell>

    <Cell title="场地详细地址" is-column custom divider :right="false" :required="formData.isSite === 1">
      <qmp-field v-model="formData.address" type="textarea" placeholder="输入内容" class="ctm-text-area" />
    </Cell>

    <Cell title="是否缴纳意向保证金" :custom="true" :right="false">
      <qmp-switch v-model="formData.isPayEarmestMoney" :active-value="1" :inactive-value="0">
        <template #background>
          <span class="qmp-switch__background"> {{ formData.isPayEarmestMoney === 1 ? '是' : '否' }}</span>
        </template>
      </qmp-switch>
    </Cell>

    <FieldDateTime
      v-if="formData.isPayEarmestMoney === 1"
      v-model="formData.payEarmestMoneyTime"
      :required="formData.isPayEarmestMoney === 1"
      title="意向保证金缴纳时间"
      placeholder="选择意向保证金缴纳时间"
      type="date"
      clear
    />

    <div v-if="isHandover">
      <div class="header"><span class="border"></span>办事处招商市场交接信息</div>

      <Cell title="是否有需要办事处协助解决的问题" :custom="true" :right="false" :required="isHandover">
        <qmp-switch v-model="handoverData.isAgencyProblemHanding" :active-value="1" :inactive-value="0">
          <template #background>
            <span class="qmp-switch__background"> {{ handoverData.isAgencyProblemHanding === 1 ? '是' : '否' }}</span>
          </template>
        </qmp-switch>
      </Cell>

      <Cell
        title="办事处协助解决问题说明"
        is-column
        custom
        divider
        :right="false"
        :required="handoverData.isAgencyProblemHanding === 1"
      >
        <qmp-field
          v-model="handoverData.agencyProblemHandingMsg"
          type="textarea"
          placeholder="输入内容"
          class="ctm-text-area"
          :maxlength="200"
        />
      </Cell>

      <Cell title="招商政策及前期招商承诺" is-column custom divider :right="false" :required="isHandover">
        <qmp-field
          v-model="handoverData.investmentCommitment"
          type="textarea"
          placeholder="输入内容"
          class="ctm-text-area"
          :maxlength="200"
        />
      </Cell>

      <Cell is-column custom title="市场信息附件" :right="false" :required="isHandover">
        <AttachmentUpload v-model="handoverData.marketFiles" multiple :objectId="id" typeCode="ACCESS049" />
      </Cell>
    </div>

    <div :class="['ctm-content-foot', { relative: keyboard.show }]">
      <div class="btn radius-larg ctm-btn-main-outline" @click="onCancel">取消</div>
      <div class="btn radius-larg ctm-btn-main" @click="onSubmit">{{ isHandover ? '提交' : '保存编辑' }}</div>
    </div>
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, getCurrentInstance, nextTick } from 'vue'
  import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router'
  import { useStore } from 'vuex'
  import Cell from '@/components/Cell/index.vue'
  import FieldDateTime from '@/components/FieldDateTime/index.vue'
  // import DealerCell from '@/components/DealerCell/index.vue'
  import FieldSelect from '@/components/FieldSelect/index.vue'
  import AttachmentUpload from '@/components/AttachmentUpload/index.vue'
  import { saveItem, editDetailItem } from '@/apis/attractInvestment/potentialCustomerFollowUp'
  import { initFormData, filterPhone, onCallPhone, isChange } from '@/utils'
  import { validIDCard } from '@/utils/validate'
  import GetKeyboardMixin from '@/utils/useKeyboard'

  interface anyObjectModle {
    id: any
    isHandover: boolean
    dictParams: object
    formData: any
    originalData: string
    handoverData: any
    detail: any
    submiting: boolean
    isEditBack: boolean
    [key: string]: any
    // dictData: any
  }

  const none: any[] = [undefined, null, '']
  export default {
    name: 'PotentialCustomerFollowUpEdit',
    components: { Cell, FieldSelect, FieldDateTime, AttachmentUpload },
    setup() {
      const $router = useRouter()
      const $route = useRoute()
      const { proxy, type }: any = getCurrentInstance()

      const { id, type: operate } = $route.query
      const $store = useStore()

      const state = reactive<anyObjectModle>({
        id: id || '',
        isHandover: (operate && operate === 'handover') || false, // 是否交接页面
        dictParams: { query: { appCode: 'slm', domainCode: 'marketing' }, type: 0 },
        formData: {
          customerName: '',
          customerIdcard: '',
          customerSex: '',
          customerAge: '',
          isHaveShop: 0,
          shopArea: '',
          followUpType: '',
          intendedLevel: '',
          intendedBusiness: [],
          agencyCode: '',
          agencyName: '',
          intendedCity: '',
          specialRemarks: '',
          customerSource: '',
          industryQualification: '',
          intendedShopArea: '',
          description: '',
          intendedMerchantDescription: '',

          isSite: 0,
          marketCode: '',
          marketName: '',
          address: '',
          isPayEarmestMoney: 0,
          payEarmestMoneyTime: ''
        },
        handoverData: {
          isAgencyProblemHanding: 0,
          agencyProblemHandingMsg: '',
          investmentCommitment: '',
          marketFiles: []
        },
        originalData: '', // 原始数据 用于对比值是否发生变化
        detail: {},
        submiting: false,
        isEditBack: false // 是否是编辑成功后返回
      })
      state.keyboard = {
        show: false
      }
      state.keyboard = GetKeyboardMixin()

      onBeforeRouteLeave((to: any, from, next) => {
        const instanceName = type?.name
        if (to.name === 'PotentialCustomerFollowUp' || to.name === 'PotentialCustomerMarketChangeDetail') {
          $store.commit('routerKeep/removeCache', instanceName)
          if (state.isEditBack || isChange(state.formData, state.originalData)) next()
          else {
            // 阻止返回
            proxy.$dialog
              .confirm({
                title: '当前编辑数据未保存，是否确认退出？',
                theme: 'round-button',
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                showCancelButton: true,
                closeOnPopstate: false
              })
              .then(() => {
                next()
              })
              .catch(() => {
                next(false)
              })
          }
        } else {
          $store.commit('routerKeep/resetCache', instanceName)
          next()
        }
      })

      const getDetail = () => {
        const id = `${state.id}`

        editDetailItem(id, state.isHandover).then((res: any) => {
          state.detail = res.data
          initFormData(res.data, state.formData)

          const { isHaveShop, isSite, isPayEarmestMoney, isAgencyProblemHanding } = res.data
          if (none.includes(isHaveShop)) state.formData.isHaveShop = 0
          if (none.includes(isSite)) state.formData.isSite = 0
          // if (none.includes(isPayEarmestMoney)) state.formData.isPayEarmestMoney = 0
          state.formData.isPayEarmestMoney = Number(isPayEarmestMoney)
          if (state.isHandover) {
            initFormData(res.data, state.handoverData)
            if (none.includes(isAgencyProblemHanding)) state.handoverData.isAgencyProblemHanding = 0
          }

          state.originalData = JSON.stringify(state.formData)
        })
      }

      // 选择特许经营市场
      const onClickToChoice = () => {
        $router.push({
          path: '/potentialCustomerFollowUp/marketChoice'
        })
      }

      proxy.$SimpleEvents.registerEvent('update', (row: any) => {
        const data: any = state.formData
        const detailData: any = state.detail

        data.marketCode = row.marketCode
        data.marketName = row.marketName
        state.formData = data

        detailData.marketNatrue = row.marketNatrue || ''
        detailData.cityLevel = row.cityLevel || ''

        state.detail = detailData
      })

      const onCancel = () => {
        // console.log('onCancel')
        $router.goBack()
      }

      const onSubmit = () => {
        // console.log('onSubmit')
        if (state.submiting) return
        let data = { id: state.id, ...state.formData, intendedBusiness: state.formData.intendedBusiness.join(',') }
        if (state.isHandover) {
          data = { ...data, ...state.handoverData }
        }
        const regArea = /^[1-9][0-9]*([\.][0-9]{1,2})?$/
        let regAge = /^(?:[1-9][0-9]?|1[01][0-9]|120)$/
        if (state.isHandover) {
          if (none.includes(data.customerName)) {
            proxy.$toast('请输入客户名称')
            return
          }
          if (none.includes(data.customerIdcard)) {
            proxy.$toast('请输入身份证号')
            return
          }

          if (data.customerIdcard && !validIDCard(data.customerIdcard)) {
            proxy.$toast('请输入正确的身份证号')
            return
          }

          if (none.includes(data.customerSex)) {
            proxy.$toast('请选择性别')
            return
          }

          if (none.includes(data.customerAge)) {
            proxy.$toast('请输入年龄')
            return
          }

          // if (data.customerAge && !regAge.test(data.customerAge)) {
          //   proxy.$toast('年龄输入不合法')
          //   return
          // }

          if (data.shopArea && !regArea.test(data.shopArea)) {
            proxy.$toast('店面总面积输入不合法')
            return
          }

          if (none.includes(data.intendedBusiness)) {
            proxy.$toast('请选择意向经营业务类型')
            return
          }

          if (none.includes(data.agencyCode)) {
            proxy.$toast('请选择所属办事处')
            return
          }

          if (none.includes(data.intendedShopArea)) {
            proxy.$toast('请输入意向开店面积')
            return
          }

          if (!regArea.test(data.intendedShopArea)) {
            proxy.$toast('意向开店面积输入不合法')
            return
          }

          if (none.includes(data.intendedMerchantDescription)) {
            proxy.$toast('请输入意向商家情况描述')
            return
          }

          if (none.includes(data.marketCode)) {
            proxy.$toast('请选择特许经营市场')
            return
          }

          if (none.includes(data.isSite)) {
            proxy.$toast('请选择是否有场地')
            return
          }

          if (data.isSite === 1 && none.includes(data.address)) {
            proxy.$toast('请输入场地详细地址')
            return
          }

          if (data.isPayEarmestMoney === 1 && none.includes(data.payEarmestMoneyTime)) {
            proxy.$toast('请选择意向保证金缴纳时间')
            return
          }

          if (none.includes(data.isAgencyProblemHanding)) {
            proxy.$toast('请选择是否有需要办事处协助解决的问题')
            return
          }

          if (data.isAgencyProblemHanding === 1 && none.includes(data.agencyProblemHandingMsg)) {
            proxy.$toast('请输入办事处协助解决问题说明')
            return
          }
          if (none.includes(data.investmentCommitment)) {
            proxy.$toast('请输入招商政策及前期招商承诺')
            return
          }
          if (!data.marketFiles.length) {
            proxy.$toast('请上传市场信息附件')
            return
          }
        } else {
          if (data.customerIdcard && !validIDCard(data.customerIdcard)) {
            proxy.$toast('请输入正确的身份证号')
            return
          }

          // if (data.customerAge && !regAge.test(data.customerAge)) {
          //   proxy.$toast('年龄输入不合法')
          //   return
          // }

          if (data.shopArea && !regArea.test(data.shopArea)) {
            proxy.$toast('店面总面积输入不合法')
            return
          }

          if (data.intendedShopArea && !regArea.test(data.intendedShopArea)) {
            proxy.$toast('意向开店面积输入不合法')
            return
          }
        }
        state.submiting = true
        saveItem(data, state.isHandover)
          .then((res: any) => {
            if (res.success === 1) {
              proxy.$toast(!state.isHandover ? '编辑成功' : '交接成功')
              proxy.$SimpleEvents.emit('refreshCustomerChangeItem')

              nextTick(() => {
                state.isEditBack = true
                $router.goBack()
              })
              state.submiting = false
            }
          })
          .catch((e: any) => {
            if (e) proxy.$toast(e)
            state.submiting = false
          })
      }

      getDetail()
      return {
        ...toRefs(state),
        onCancel,
        onSubmit,
        onClickToChoice,
        filterPhone,
        onCallPhone
      }
    }
  }
</script>

<style lang="less" scoped>
  .user-info {
    margin-top: 8px;
    margin-bottom: 8px;
    background: var(--bg-global-weaker);
    padding: 16px 14px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .left {
      flex: 1;
      margin-right: 8px;
      font: var(--font-main-title-strengthen);
      color: var(--texticon-default-strong);

      span {
        margin-left: 6px;
        font: var(--font-main-title-body);
        color: var(--texticon-default-stronger);
      }
    }

    .right {
      width: 40px;
      height: 40px;
      background: var(--texticon-color-brand-normal);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;

      img {
        width: 24px;
        height: 24px;
      }
    }
  }

  .header {
    margin-top: 8px;
    height: 20px;
    font: var(--font-main-body);
    color: var(--texticon-default-stronger);
    background: var(--bg-global-weaker);
    padding: 8px 7px;

    display: flex;
    align-items: center;
    position: relative;

    .border {
      display: inline-block;
      width: 3px;
      height: 16px;
      margin-right: 4px;
      background-color: #3dc094;
      vertical-align: -4px;
    }

    &::after {
      position: absolute;
      content: '';
      width: calc(100% - 28px);
      height: 1px;
      bottom: 0;
      left: 14px;
      background: var(--divisionline-weak);
    }
  }

  .other-cell {
    /deep/ .sub-label {
      width: 240px;
      white-space: pre-wrap;
    }
  }
</style>
